//
//  DCPaymentView.m
//  DCPayAlertDemo
//
//  Created by dawnnnnn on 15/12/9.
//  Copyright © 2015年 dawnnnnn. All rights reserved.
//

#import "DCPaymentView.h"

#define TITLE_HEIGHT 46
#define PAYMENT_WIDTH [UIScreen mainScreen].bounds.size.width-80
#define PWD_COUNT 6
#define DOT_WIDTH 10
#define KEYBOARD_HEIGHT 216
#define KEY_VIEW_DISTANCE 100
#define ALERT_HEIGHT 140


@interface DCPaymentView ()<UITextFieldDelegate>
{
    NSMutableArray *pwdIndicatorArr;
}
@property (nonatomic, strong) UIView *paymentAlert, *inputView;
@property (nonatomic, strong) UIButton *closeBtn, *yesBtn;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *pwdTextField;

@end

@implementation DCPaymentView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.3f];
        _numOfContent = 20;
        [self drawView];
        
    }
    return self;
}

- (void)drawView {
    if (!_paymentAlert) {
        _paymentAlert = [[UIView alloc]initWithFrame:CGRectMake(40, [UIScreen mainScreen].bounds.size.height-KEYBOARD_HEIGHT-KEY_VIEW_DISTANCE-ALERT_HEIGHT, [UIScreen mainScreen].bounds.size.width-80, ALERT_HEIGHT)];
        _paymentAlert.layer.cornerRadius = 5.f;
        _paymentAlert.layer.masksToBounds = YES;
        _paymentAlert.backgroundColor = [UIColor colorWithWhite:1. alpha:.95];
        [self addSubview:_paymentAlert];
        
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, PAYMENT_WIDTH, TITLE_HEIGHT)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor darkGrayColor];
        _titleLabel.font = [UIFont systemFontOfSize:17];
        [_paymentAlert addSubview:_titleLabel];
        
        //关闭
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setFrame:CGRectMake(0, 0, TITLE_HEIGHT, TITLE_HEIGHT)];
        [_closeBtn setTitle:@"╳" forState:UIControlStateNormal];
        [_closeBtn setTitleColor:GH forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        _closeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_paymentAlert addSubview:_closeBtn];

        _pwdTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, TITLE_HEIGHT + 10, PAYMENT_WIDTH - 20, 40)];
        [self.paymentAlert addSubview:_pwdTextField];
        _pwdTextField.delegate = self;
        _pwdTextField.borderStyle = UITextBorderStyleRoundedRect;
        
        //确定
        _yesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_yesBtn setFrame:CGRectMake(0, 0, TITLE_HEIGHT, TITLE_HEIGHT)];
        _yesBtn.center = CGPointMake(_pwdTextField.center.x, _pwdTextField.center.y + 40);
        [_yesBtn setTitle:@"确 定" forState:UIControlStateNormal];
        [_yesBtn setTitleColor:HS forState:UIControlStateNormal];
        [_yesBtn addTarget:self action:@selector(yesAction) forControlEvents:UIControlEventTouchUpInside];
        _yesBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_paymentAlert addSubview:_yesBtn];
        
        
        
    }
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextFieldTextDidChangeNotification" object:_pwdTextField];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.pwdTextField) {
        if (self.pwdTextField.text.length > _numOfContent) {
       
        if (textField.text.length > _numOfContent){
            
                   return NO;
        }
        }
        
    }
    
    return YES;
}



- (void)show {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    
    _paymentAlert.transform = CGAffineTransformMakeScale(1.21f, 1.21f);
    _paymentAlert.alpha = 0;

    
    [UIView animateWithDuration:.7f delay:0.f usingSpringWithDamping:.7f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [_pwdTextField becomeFirstResponder];
        _paymentAlert.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
        _paymentAlert.alpha = 1.0;
    } completion:nil];
}

- (void)dismiss {
    [_pwdTextField resignFirstResponder];
    [UIView animateWithDuration:0.3f animations:^{
        _paymentAlert.transform = CGAffineTransformMakeScale(1.21f, 1.21f);
        _paymentAlert.alpha = 0;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)yesAction {

    [_pwdTextField resignFirstResponder];
    [UIView animateWithDuration:0.3f animations:^{
        _paymentAlert.transform = CGAffineTransformMakeScale(1.21f, 1.21f);
        _paymentAlert.alpha = 0;
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        _completeHandle(_pwdTextField.text);
        
    }];
}

- (void)setDotWithCount:(NSInteger)count {
    for (UILabel *dot in pwdIndicatorArr) {
        dot.hidden = YES;
    }
    
    for (int i = 0; i< count; i++) {
        ((UILabel*)[pwdIndicatorArr objectAtIndex:i]).hidden = NO;
    }
}

- (void)setTextFieldKeyBordToNum {

    _pwdTextField.keyboardType = UIKeyboardTypeNumberPad;
    
}

//- (void)ssetTextField

#pragma mark - 
- (void)setTitle:(NSString *)title {
    if (_title != title) {
        _title = title;
        _titleLabel.text = _title;
    }
}


-(void) textFieldDidChanged:(UITextField *) textField
{
    NSString *toBeString=textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange=[textField markedTextRange];
    UITextPosition  *position=[textField positionFromPosition:selectedRange.start offset:0];
    
    //没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position) {
        
        //编写正则表达式：只能是数字或英文，或两者都存在
        NSString *regex=@"^[\u4E00-\u9FA5]+$";
        
        //创建谓词对象设定条件的表达式
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF MATCHES%@",regex];
        
        NSMutableString *muStr=[[NSMutableString alloc]initWithString:toBeString];
        NSMutableArray *ranges=[[NSMutableArray alloc]init];
        for (int i=0; i<toBeString.length; i++) {
            
            NSString *str=[toBeString substringWithRange:NSMakeRange(i, 1)];
            
            //对字符串进行判断
            if (![predicate evaluateWithObject:str]) {
                
                if (![ranges containsObject:str]) {
                    [ranges addObject:str];
                }
            }
        }
        for (NSString *string in ranges) {
            [muStr  replaceOccurrencesOfString:string withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, muStr.length)];
        }
        if (muStr.length >10) {
            
            NSRange rangelndex=[muStr rangeOfComposedCharacterSequenceAtIndex:10];
            
            if (rangelndex.length ==1) {
                textField.text=[muStr substringToIndex:10];
            }else{
                
                NSRange  rangeRange=[muStr rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 10)];
                textField.text=[muStr substringWithRange:rangeRange];
            }
        }
        else{
            
            textField.text=muStr;
        }
    }
}



#pragma mark - Notification Method
-(void)textFiledEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > _numOfContent)
            {
                textField.text = [toBeString substringToIndex:_numOfContent];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > _numOfContent)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_numOfContent];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:_numOfContent];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _numOfContent)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}


//把回车键当做退出键盘的响应键  textView退出键盘的操作

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    
    
    
    if ([@"\n" isEqualToString:text] == YES)
        
    {
        
        [textView resignFirstResponder];
        
        
        
        
        
        return NO;
        
    }
    
    
    
    return YES;
    
}




@end